﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace NetworkTest
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpListener listener = new TcpListener(IPAddress.Any, 5000);
            listener.Start();
            TaskFactory tasks = new TaskFactory();
            string ipaddress = string.Empty;
            TcpClient client = null;
            while (true)
            {
                Console.WriteLine("等待连接。。。");
                client = listener.AcceptTcpClient();

                tasks.StartNew(() => HandleClient(client, ipaddress)).Wait();
            }
        }

        private static void HandleClient(TcpClient client, string ipaddress)
        {
            lock (client)
            {
                if (client == null)
                {
                    return;
                }

                // Buffer for reading data
                Byte[] bytes = new Byte[1024];
                String data = null;

                // Enter the listening loop.
                while (client.Connected)
                {


                    data = null;

                    NetworkStream stream = client.GetStream();

                    int i;

                    if ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        data = Encoding.UTF8.GetString(bytes, 0, i);
                        byte[] msg = Encoding.UTF8.GetBytes(data);

                        stream.Write(msg, 0, msg.Length);//原样返回
                        Console.WriteLine(client.Client.RemoteEndPoint.ToString().Split(':')[0] + " : "+ data);
                    }
                   
                }
            }
        }
    }
}
